/*
 * @FileName: [LoginFilter.java]
 * 
 * @Package com.bcinfo.upp.admin.ac.filter
 * 
 * 
 * Copyright (c) 2011-2015 BCINFO Technology Limited Com. All rights reserved.
 * 
 * This software is the confidential and proprietary information of BCINFO Technology Limited Company ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in accordance with the terms of the contract agreement you entered into with RKY.
 * 
 * $Rev: 42 $ $LastChangedDate: 2013-10-12 10:19:36 +0800 (星期六, 12 十月 2013) $ $LastChangedBy: wanggc $
 * 
 * @category bcinfo-upp
 * 
 * @version 1.1
 * 
 * @author $Author: yangzq$
 * 
 * Change History:[Formatter: author date description] <br/> 1 2 3
 */

package com.bcinfo.iccard.admin.ac.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.bcinfo.iccard.admin.common.Constants;

/**
 * 登录拦截器 <br/>
 * <p>
 * Description:<br/>
 * <p>
 * 拦截所有url，非登录页面如果为登录，跳转到登录页面
 * 
 * <p>
 * For Examples <br/>
 * 
 * <PRE>
 *      <filter>
 *         <filter-name>loginFilter</filter-name>
 *         <filter-class>com.bcinfo.upp.admin.ac.filter.LoginFilter</filter-class>
 *         <init-param>
 *             <param-name>exceptUri</param-name>
 *             <param-value>/login;/logout;/imageCode</param-value>
 *         </init-param>
 *         </filter>
 *         <filter-mapping>
 *             <filter-name>loginFilter</filter-name>
 *             <url-pattern>/*</url-pattern>
 *         </filter-mapping>
 * </PRE>
 * <p>
 */
public class LoginFilter implements Filter
{
    /**
     * 不需要登录的uri路径
     */
    private String _exceptUri = "/login.jsp;";

    /*
     * (non-Javadoc) Description: <br/>
     * 
     * @see javax.servlet.Filter#destroy()
     */
    public void destroy()
    {
    }

    /*
     * (non-Javadoc) Description: <br/>
     * 
     * @param arg0
     * 
     * @param arg1
     * 
     * @param arg2
     * 
     * @throws IOException
     * 
     * @throws ServletException
     * 
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    @SuppressWarnings("unchecked")
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,
            ServletException
    {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String reqUri = request.getRequestURI();
        if (reqUri.endsWith(".jsp") || reqUri.endsWith(".html") || reqUri.indexOf(".") == -1)
        {
            reqUri = reqUri.replace(request.getContextPath(), "");
            List<String> exceptUriList = Arrays.asList(_exceptUri.split(";"));
            if (!exceptUriList.contains(reqUri) && null == request.getSession().getAttribute(Constants.CURRENT_USER))
            {
                if (request.getHeader("x-requested-with") != null
                        && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest"))
                {
                    response.getWriter().print("session timeout");
                    return;
                }
                else
                {
                    response.sendRedirect(request.getContextPath() + "/login.jsp");
                }
                return;
            }
        }

        // 验证改页面是否重复提交
        if (reqUri.indexOf(".") == -1)
        {
            Object obj = request.getSession().getAttribute("tokenStore");
            String token = req.getParameter("formToken");
            Map<String, Date> tokenStore;

            if (obj != null && StringUtils.isNotBlank(token))
            {
                tokenStore = (Map<String, Date>) obj;

                if (tokenStore.containsKey(token))
                {
                    tokenStore.remove(token);
                }
                else
                {
                    return;
                }
            }
        }

        chain.doFilter(req, resp);
    }

    /*
     * (non-Javadoc) Description: <br/>
     * 
     * @param arg0
     * 
     * @throws ServletException
     * 
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    public void init(FilterConfig config) throws ServletException
    {
        String loginUriParame = config.getInitParameter("exceptUri");
        if (null != loginUriParame)
        {
            _exceptUri += loginUriParame;
        }
    }

}
